#include <stdio.h>
#include <unistd.h>
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_gpio.h"
#include <hi_types_base.h>
#include <hi_io.h>
#include <hi_gpio.h>
#include <hi_adc.h>

#define LED_INTERVAL_TIME_US 300000
#define VOICE_TASK_STACK_SIZE 4096
#define VOICE_TASK_PRIO 25
#define VOICE_LED_GPIO 10
#define VOICE_AD_IN 11
#define LED_OFF 1
#define LED_ON 0

void ledOn(unsigned char lednum)
{
    IoTGpioSetOutputVal(lednum, LED_ON);
}
void ledOff(unsigned char lednum)
{
    IoTGpioSetOutputVal(lednum, LED_OFF);
}
void voice_Init(void)
{
    IoTGpioInit(VOICE_LED_GPIO);
    IoTGpioSetDir(VOICE_LED_GPIO,IOT_GPIO_DIR_OUT); 
    IoTGpioSetOutputVal(VOICE_LED_GPIO,LED_OFF);
    ledOff(VOICE_LED_GPIO);

    IoTGpioInit(VOICE_AD_IN);
    IoTGpioSetDir(VOICE_AD_IN, IOT_GPIO_DIR_IN);
    hi_io_set_func(VOICE_AD_IN, HI_IO_FUNC_GPIO_11_GPIO);
}

static hi_u16 AdcGPIORead()
{
    hi_u32 ret;
    hi_u16 val;
    ret = hi_adc_read(HI_ADC_CHANNEL_5, &val, HI_ADC_EQU_MODEL_1,HI_ADC_CUR_BAIS_DEFAULT,0);
    if (ret != HI_ERR_SUCCESS) {
        printf("ADC Read Failn\n");
        return 0;
    }
    return val;
}

static void *VoiceTask(const char *arg)
{
    (void)arg;
    while (1)
    {
        printf("read adc");
        hi_u16 voice =AdcGPIORead();
        printf("voice is %d\n", voice);
        if(voice > 280)
        {
            ledOn(VOICE_LED_GPIO);
            printf("voice led on\n");
        }
        else
        {
            ledOff(VOICE_LED_GPIO);
            printf("voice led off\n");
        }
        usleep(LED_INTERVAL_TIME_US);
    }
    return NULL;
}

static void VoiceExampleEntry(void)
{
    osThreadAttr_t attr;

    voice_Init();

    attr.name ="VoiceTask";
    attr.attr_bits = 0U;
    attr.cb_mem =NULL;
    attr.cb_size =0U;
    attr.stack_mem =NULL;
    attr.stack_size = VOICE_TASK_STACK_SIZE;
    attr.priority =VOICE_TASK_PRIO;

    if (osThreadNew((osThreadFunc_t)VoiceTask,NULL,&attr) == NULL){
        printf("[VoiceExample] Falied to create VoiceTask!\n");
    }
}

SYS_RUN(VoiceExampleEntry);

